﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums;
using ZBJF.Warranty.Model;
using PageAction = ZBJF.Warranty.Model.PageAction;

namespace ZBJF.Warranty.WebProvider.AdminPemission
{
    public class RightHelper
    {

        private static RightHelper _instance;

        public static RightHelper Instance
        {
            get
            {
                return _instance ?? (_instance = new RightHelper());
            }
        }
        #region 得到当前登陆的用户角色ID
        /// <summary>
        /// 得到当前登陆的用户角色ID
        /// </summary>
        /// <returns></returns>
        public List<int> GetCurrentUserRoleIDs()
        {
            var userID = WebContext.Instance.CurrentUser == null || WebContext.Instance.CurrentUser == null ? -1 : WebContext.Instance.CurrentUser.ID;
            return GetAllRoleToSystemUsers().Where(p => p.UserID == userID)
                    .Select(i => i.RoleID)
                    .ToList();
        }
        #endregion

        #region 得到所有的操作按钮
        /// <summary>
        /// 得到所有的操作按钮
        /// </summary>
        /// <returns></returns>
        public List<string> GetAllActionCode()
        {
            return GetAllPageAction().Select(i => i.ActionCode).ToList();
        }
        #endregion



        #region 得到请求的页面用户有权限的按钮
        public List<string> GetCurrentUserHasRightActionCode(int pageID)
        {
            var pageToActions = GetAllPageToAction().Where(
                p => p.PageID == pageID).ToList();
            if (pageToActions.Count < 1)//如果页面没有绑定按钮，则视为页面没有做权限控制
                return GetAllActionCode();

            var unbindActionCode = GetAllActionCode().Except(pageToActions.Select(o => o.PageAction.ActionCode)).ToList();
            var currentUserRoleIDs = GetCurrentUserRoleIDs();
            var r = GetAllRoleToPageToAction().Where(
                p => p.PageToAction.PageID == pageID && currentUserRoleIDs.Contains(p.RoleID) && !unbindActionCode.Contains(p.PageToAction.PageAction.ActionCode))
                .Select(o => o.PageToAction.PageAction.ActionCode)
                .ToList();

            return r;
        }
        #endregion

        #region 得到用户没有权限的按钮
        /// <summary>
        /// 得到用户没有权限的按钮
        /// </summary>
        /// <param name="pageID"></param>
        /// <returns></returns>
        public List<string> GetPageAcion(int pageID)
        {
            return GetAllPageToAction().Where(p => p.PageID == pageID).Select(o => o.PageAction.ActionCode).ToList();
        }
        public List<string> GetCurrentUserNoRightActionCode(int pageID)
        {
            return GetAllActionCode().Except(GetCurrentUserHasRightActionCode(pageID)).ToList();
        }
        #endregion

        #region 得到用户没有权限的按钮
        public bool CanViewPage(int pageID)
        {
            return GetPageAcion(pageID).Except(GetCurrentUserNoRightActionCode(pageID)).ToList().Count > 0;
        }
        #endregion

        #region 得到用户有权限的菜单

        /// <summary>
        /// 得到用户有权限的菜单
        /// </summary>
        /// <returns></returns>
        public List<PageMenu> GetRightOperationMenu()
        {
            bool openRightControl = false;
            bool.TryParse(ConfigurationManager.AppSettings["NeedAuthentication"], out openRightControl);
            var rightListPageId = GetListPageID(GetCurrentUserRoleIDs());
            return GetAllPageMenuByApplicationType().Where(p => p.IsShow && (!openRightControl || IsSupperAdmin || rightListPageId.Contains(p.ID))).ToList();
        }
        #endregion

        #region 得到当前用户有权限查看的菜单
        /// <summary>
        /// 得到当前用户有权限查看的菜单
        /// </summary>
        /// <param name="listRoleID">角色ID列表</param>
        /// <returns></returns>
        public List<int> GetListPageID(List<int> listRoleID = null)
        {
            return
                GetAllRoleToPageToAction().Where(
                    p => listRoleID == null || listRoleID.Contains(p.RoleID))
                    .Select(o => o.PageToAction.PageID)
                    .ToList();
        }
        #endregion

        #region 判断当前用户是否是超级管理员
        /// <summary>
        /// 判断当前用户是否是超级管理员
        /// </summary>
        public bool IsSupperAdmin
        {
            get
            {
                if (WebContext.Instance.CurrentUser == null)
                    return false;
                var role = GetAllRoleToSystemUsers().FirstOrDefault(o => o.UserID == WebContext.Instance.CurrentUser.ID);
                if (role == null)
                    return false;
                return role.SystemRole.RoleCode.Equals(SystemRoleEnums.SuperAdmin.ToString(),
                    StringComparison.OrdinalIgnoreCase);
            }
        }
        #endregion

        #region 缓存数据

        public List<PageAction> GetAllPageAction()
        {
            return CacheHelper.Instance.GetDataFromCache("AllPageAction",
                () => ServiceFactory.PageActionServiceInstance.LoadEntities(p => true)
                    .ToList());
        }
        #region 得到用户有权限的菜单
        public List<PageMenu> GetAllPageMenu()
        {
            return CacheHelper.Instance.GetDataFromCache("AllPageMenu",
                () => ServiceFactory.PageMenuServiceInstance.LoadAllPageMenus().ToList());
        }

        public List<PageMenu> GetAllPageMenuByApplicationType()
        {
            if (WebContext.Instance.CurrentUser == null)
                return new List<PageMenu>();
            return CacheHelper.Instance.GetDataFromCache("AllPageMenuByApplicationType",
                () => ServiceFactory.PageMenuServiceInstance.LoadBy((ApplicationType)WebContext.Instance.CurrentUser.BelongApplicationType, true).ToList());
        }
        #endregion

        public List<PageToAction> GetAllPageToAction()
        {
            return CacheHelper.Instance.GetDataFromCache("AllPageToAction",
                () => ServiceFactory.PageToActionServiceInstance.LoadEntities(p => true).ToList());
        }

        public List<RoleToPageToAction> GetAllRoleToPageToAction()
        {
            return CacheHelper.Instance.GetDataFromCache("AllRoleToPageToAction",
                () => ServiceFactory.RoleToPageToActionServiceInstance.LoadEntities(p => true).ToList());
        }
        public List<RoleToSystemUser> GetAllRoleToSystemUsers()
        {
            return CacheHelper.Instance.GetDataFromCache("AllRoleToSystemUsers",
                () => ServiceFactory.RoleToSystemUserServiceInstance.LoadEntities(p => true).ToList());
        }

        #region 获取除去超级管理员的所有角色
        /// <summary>
        /// 获取除去超级管理员的所有角色
        /// </summary>
        /// <returns></returns>
        public List<SystemRole> GetAllRoles()
        {
            return CacheHelper.Instance.GetDataFromCache("AllRoles",
              () => ServiceFactory.SystemRoleServiceInstance.LoadEntities(o => o.IsAvailable).ToList());
        }
        #endregion

        #endregion

    }
}